package study.eggs.springcloud.gateway.auth;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Slf4j
@Component
public class AuthFactory implements ApplicationContextAware {

    public static Map<String, AuthService> AUTH_SERVICE_MAP = new ConcurrentHashMap<>();

    private static ApplicationContext CTX;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        CTX = applicationContext;
    }

    @PostConstruct
    public void init() {
        AUTH_SERVICE_MAP = CTX.getBeansOfType(AuthService.class);
        log.info(">>>>>>>>>> {}", AUTH_SERVICE_MAP);
    }

    public static AuthService getAuthService(String type) {
        return AUTH_SERVICE_MAP.get(type);
    }

    public static List<AuthService> getAuthServiceLt(List<String> typeLt) {
        if (CollectionUtil.isEmpty(typeLt)) {
            return null;
        }
        return typeLt.stream()
                .map(AuthFactory::getAuthService)
                .collect(Collectors.toList());
    }
}
